657. Robot Return to Origin

题目 657. Robot Return to Origin

image-d1ba545a

思路分析

image-0a34d238
class Solution {
    public boolean judgeCircle(String moves) {
        StringBuilder stack = new StringBuilder();
        for(int i=0;i<moves.length();i++){
            char cur = moves.charAt(i);
            if(stack.length()>0){
                char top=stack.charAt(stack.length()-1);
                if(isPair(top,cur)){
                    stack.deleteCharAt(stack.length()-1);
                    continue;
                }
            }
            stack.append(cur);
        }
        return stack.length()==0;
    }

    private boolean isPair(char a,char b){
        if (a == 'U' && b == 'D') return true;
        if (a == 'D' && b == 'U') return true;
        if (a == 'L' && b == 'R') return true;
        if (a == 'R' && b == 'L') return true;
        return false;
    }
}

但其实发现会错 聪明反被聪明误了

栈的一个核心特性是必须消除相邻(或经消除后相邻)的元素。但这道题是二维平面的移动,X轴 的移动和 Y轴 的移动是互不干扰的,中间隔着别的方向也能抵消。

其实只需要看数量++ –-最后等不等于0即可

代码实现

class Solution {
    public boolean judgeCircle(String moves) {
        int[] cnt = new int[26];

        for(char c:moves.toCharArray()){
            cnt[c-'A']++;
        }

        return  cnt['U'-'A']==cnt['D'-'A'] &&
                cnt['L'-'A']==cnt['R'-'A'];
    }
}
class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        for (int i = 0; i < moves.length(); i++) {
            switch (moves.charAt(i)) {
                case 'U': y++; break;
                case 'D': y--; break;
                case 'L': x--; break;
                case 'R': x++; break;
            }
        }
        return x == 0 && y == 0;
    }
}

同类题型

视频讲解